package com.ryder.petmatediarybackend.module.user.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.ryder.petmatediarybackend.common.response.Result;
import com.ryder.petmatediarybackend.module.file.enums.FileBizTypeEnum;
import com.ryder.petmatediarybackend.module.file.service.FileUploadService;
import com.ryder.petmatediarybackend.module.file.vo.FileUploadVO;
import com.ryder.petmatediarybackend.module.pet.service.SysUserService;
import com.ryder.petmatediarybackend.module.user.dto.ChangePasswordDTO;
import com.ryder.petmatediarybackend.module.user.dto.UpdateProfileDTO;
import com.ryder.petmatediarybackend.module.user.vo.UserProfileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 描述：用户个人信息管理 Controller
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-10-31 08:00:00
 */
@Slf4j
@Tag(name = "用户个人信息管理", description = "用户个人信息查看、编辑、头像上传、密码修改接口（需要登录）")
@RestController
@RequestMapping("/user/profile")
@SecurityRequirement(name = "Authorization")
@RequiredArgsConstructor
public class UserProfileController {

    private final SysUserService sysUserService;

    private final FileUploadService fileUploadService;

    @Operation(summary = "获取个人信息", description = "获取当前登录用户的详细信息（包含统计数据），需要 user:profile:view 权限")
    @SaCheckPermission("user:profile:view")
    @GetMapping("/detail")
    public Result<UserProfileVO> getUserProfile() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[个人信息] 用户ID={} 执行获取个人信息, 方法=getUserProfile", userId);
        UserProfileVO vo = sysUserService.getUserProfile(userId);
        return Result.ok(vo);
    }

    @Operation(summary = "更新个人信息", description = "更新当前登录用户的个人信息，需要 user:profile:update 权限")
    @SaCheckPermission("user:profile:update")
    @PutMapping("/update")
    public Result<Void> updateUserProfile(@Valid @RequestBody UpdateProfileDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[个人信息] 用户ID={} 执行更新个人信息, 方法=updateUserProfile, 入参={}", userId, dto);
        sysUserService.updateUserProfile(userId, dto);
        log.info("[个人信息] 用户ID={} 更新个人信息成功", userId);
        return Result.ok();
    }

    @Operation(summary = "上传头像", description = "上传用户头像，需要 user:profile:avatar 权限")
    @SaCheckPermission("user:profile:avatar")
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(
            @Parameter(description = "头像文件", required = true)
            @RequestParam("file") MultipartFile file) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[个人信息] 用户ID={} 执行上传头像, 方法=uploadAvatar, 文件名={}", userId, file.getOriginalFilename());

        // 上传文件
        List<FileUploadVO> result = fileUploadService.uploadFiles(
                List.of(file),
                FileBizTypeEnum.USER_AVATAR.getCode(),
                userId
        );

        // 更新用户头像URL
        String avatarUrl = result.get(0).getUrl();
        sysUserService.updateAvatar(userId, avatarUrl);

        log.info("[个人信息] 用户ID={} 上传头像成功, avatarUrl={}", userId, avatarUrl);
        return Result.ok(avatarUrl);
    }

    @Operation(summary = "修改密码", description = "修改当前登录用户的密码，需要 user:profile:password 权限")
    @SaCheckPermission("user:profile:password")
    @PostMapping("/change-password")
    public Result<Void> changePassword(@Valid @RequestBody ChangePasswordDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[个人信息] 用户ID={} 执行修改密码, 方法=changePassword", userId);
        sysUserService.changePassword(userId, dto);
        log.info("[个人信息] 用户ID={} 修改密码成功", userId);
        return Result.ok();
    }
}

